// 首字母大写的才是 public
package main

import (
	"encoding/json"
	"fmt"
)

type OrderItem struct {
	ID    string  `json:"id"`
	Name  string  `json:"name"`
	Price float64 `json:"price"`
}

type Order struct {
	ID         string      `json:"id"`
	Item       []OrderItem `json:"item"`
	Quantity   int         `json:"quantity"`
	TotalPrice float64     `json:"total_price,omitempty"`
}

func unmarshal() {
	s := `{"id":"1234","item":[{"id":"12301","name":"LearnGo01","price":12301},{"id":"12302","name":"LearnGo02","price":12302}],"quantity":3}`
	var o Order
	err := json.Unmarshal([]byte(s), &o)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", o)

}

func marshal() {
	order := Order{
		ID: "1234",
		Item: []OrderItem{
			{
				ID:    "12301",
				Name:  "LearnGo01",
				Price: 12301,
			},
			{
				ID:    "12302",
				Name:  "LearnGo02",
				Price: 12302,
			},
		},
		Quantity: 3,
	}
	// Go 数据
	fmt.Printf("%+v\n", order)

	// JSON 格式
	marshal, err := json.Marshal(order)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", marshal)

}

func main() {
	unmarshal()
}
